import {
  type FormInstance,
  Form,
  message,
  Button,
  Empty,
  Skeleton,
  FloatButton,
  Checkbox,
} from 'antd';
import { createList } from './model';
import {
  createMetroLineStation,
  deleteMetroLineStation,
  getMetroLineStation,
  getMetroLineStations,
  updateMetroLineStation,
} from '@/servers/metro/lineStation';
import { useParams } from 'react-router-dom';
import StationLine, { Station } from '@/pages/metro/line/[id]/components/StationLine';
import LineHead, { LineData } from '@/pages/metro/line/[id]/components/LineHead';
import { PlusOutlined, RedoOutlined } from '@ant-design/icons';
import MapTianditu from './components/MapTianditu';
import { Coordinate } from 'ol/coordinate';
import { updateMetroLineRoute } from '@/servers/metro/line';

function Page() {
  const { id } = useParams();
  const { permissions, isPhone } = useCommonStore();

  const initCreate = {};

  // 权限前缀
  const permissionPrefix = '/metro/line/station';

  // 权限
  const pagePermission: PagePermission = {
    page: checkPermission(`${permissionPrefix}`, permissions),
    create: checkPermission(`${permissionPrefix}/create`, permissions),
    update: checkPermission(`${permissionPrefix}/update`, permissions),
    delete: checkPermission(`${permissionPrefix}/delete`, permissions),
  };

  const { t } = useTranslation();
  const createFormRef = useRef<FormInstance>(null);
  const [messageApi, contextHolder] = message.useMessage();
  const [isFetch, setFetch] = useState(false);
  const [isLoading, setLoading] = useState(false);
  const [isCreateLoading, setCreateLoading] = useState(false);
  const [isCreateOpen, setCreateOpen] = useState(false);
  const [createTitle, setCreateTitle] = useState(ADD_TITLE(t));
  const [createId, setCreateId] = useState('');
  const [createData, setCreateData] = useState<BaseFormData>(initCreate);
  const [stationsData, setStationsData] = useState<BaseFormData[]>([]);
  const [lineData, setLineData] = useState<BaseFormData>({});
  const [keepShowCreate, setKeepShowCreate] = useState(false);

  const [form] = Form.useForm();

  useSingleTab({
    fatherPath: permissionPrefix,
    zhTitle: t('metro.cityLineButton'),
    enTitle: t('metro.cityLineButton'),
  });

  const getPage = useCallback(async () => {
    if (id === undefined) return;

    try {
      setLoading(true);
      const { code, data } = await getMetroLineStations(id);
      if (Number(code) !== 200) return;
      setStationsData(data.stations || []);
      setLineData(data.line || {});
    } finally {
      setFetch(false);
      setLoading(false);
    }
  }, [id]);

  useEffect(() => {
    if (isFetch) getPage();
  }, [getPage, isFetch]);

  // 首次进入自动加载接口数据
  useEffect(() => {
    if (pagePermission.page) getPage();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pagePermission.page]);

  /** 点击新增 */
  const onCreate = () => {
    setCreateOpen(true);
    setCreateTitle(ADD_TITLE(t, `(${lineData.cityName}-${lineData.lineName})`));
    setCreateId('');
    setCreateData({
      ...initCreate,
      lineCode: lineData.id,
      sort: stationsData.length + 1,
    });
  };

  /**
   * 点击编辑
   * @param id - 唯一值
   */
  const onUpdate = async (id: string) => {
    try {
      setCreateOpen(true);
      setCreateTitle(EDIT_TITLE(t, `${lineData.cityName}-${lineData.lineName}`));
      setCreateId(id);
      setCreateLoading(true);
      const { code, data } = await getMetroLineStation(id);
      if (Number(code) !== 200) return;
      setCreateData(data);
    } finally {
      setCreateLoading(false);
    }
  };

  /** 表格提交 */
  const createSubmit = () => {
    createFormRef.current?.submit();
  };

  /** 关闭新增/修改弹窗 */
  const closeCreate = () => {
    setCreateOpen(false);
  };

  /**
   * 新增/编辑提交
   * @param values - 表单返回数据
   */
  const handleCreate = async (values: BaseFormData) => {
    try {
      setCreateLoading(true);
      const functions = () =>
        createId
          ? updateMetroLineStation(createId, values)
          : createMetroLineStation(values, `${lineData.id}`);
      const { code, message } = await functions();
      if (Number(code) !== 200) return;
      messageApi.success(message || t('public.successfulOperation'));
      if (!createId && keepShowCreate) {
        setCreateData({
          ...initCreate,
          lineCode: lineData.id,
          sort:
            (values.sort as number) > 0 ? (values.sort as number) + 1 : (values.sort as number) - 1,
        });
      } else {
        setCreateOpen(false);
      }
      getPage();
    } finally {
      setCreateLoading(false);
    }
  };

  const handleRouteUpdate = async (route: Coordinate[]) => {
    try {
      setLineData((prev) => ({ ...prev, lineRoute: route }));

      setCreateLoading(true);
      if (!id) return;
      const { code, message } = await updateMetroLineRoute(id, route);
      if (Number(code) !== 200) return;
      messageApi.success(message || t('public.successfulOperation'));
    } finally {
      setCreateLoading(false);
    }
  };

  /**
   * 点击删除
   * @param id - 唯一值
   */
  const onDelete = async (id: string) => {
    try {
      setLoading(true);
      const { code, message } = await deleteMetroLineStation(id);
      if (Number(code) === 200) {
        messageApi.success(message || t('public.successfullyDeleted'));
        getPage();
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <BaseContent isPermission={pagePermission.page}>
      {contextHolder}

      <BaseCard className={`${isPhone ? '' : 'h-100px flex flex-col justify-center'}`}>
        {isLoading ? (
          <Skeleton avatar paragraph={{ rows: 1 }} />
        ) : (
          <LineHead lineData={lineData as unknown as LineData} stationCount={stationsData.length} />
        )}
      </BaseCard>

      <div className={`overflow-auto ${isPhone ? 'flex-wrap' : 'flex'} mt-10px`}>
        <div className={`flex flex-col mb-20px ${isPhone ? 'max-h-700px' : 'h-700px mr-10px'}`}>
          <BaseCard className={`${isPhone ? '' : 'w-400px'}`}>
            <div
              className={`mb-2 flex ${pagePermission.create ? 'justify-between' : 'justify-end'}`}
            >
              {pagePermission.create && (
                <Button
                  type="primary"
                  className="small-btn"
                  icon={<PlusOutlined />}
                  onClick={onCreate}
                  loading={isLoading}
                >
                  {t('public.create')}
                </Button>
              )}
              <Button
                className="small-btn"
                icon={<RedoOutlined className="transform rotate-270" disabled={isLoading} />}
                onClick={getPage}
              >
                {t('public.refresh')}
              </Button>
            </div>
            {stationsData.length > 0 ? (
              <StationLine
                stations={(stationsData as unknown as Station[]) ?? []}
                lineCode={lineData.lineCode as string}
                lineColor={lineData.lineColor as string}
                onUpdate={pagePermission.update ? onUpdate : undefined}
                onDelete={pagePermission.delete ? onDelete : undefined}
              />
            ) : (
              <Empty />
            )}
          </BaseCard>
        </div>

        <div className="overflow-auto w-full">
          <MapTianditu
            lines={[
              {
                line: lineData as unknown as LineData,
                stations: stationsData as unknown as Station[],
              },
            ]}
            isPhone={isPhone}
            isSingle
            onLineEdit={handleRouteUpdate}
          />
        </div>
      </div>

      <BaseModal
        title={createTitle}
        open={isCreateOpen}
        confirmLoading={isCreateLoading}
        onCancel={closeCreate}
        footer={
          <div className="flex justify-between w-full">
            <div>
              {!createId && (
                <Checkbox
                  value={keepShowCreate}
                  onChange={(e) => setKeepShowCreate(e.target.checked)}
                >
                  {t('public.keepShow')}
                </Checkbox>
              )}
            </div>
            <div className="flex gap-10px">
              <Button onClick={closeCreate}>{t('public.cancel')}</Button>
              <Button type="primary" onClick={createSubmit}>
                {t('public.confirm')}
              </Button>
            </div>
          </div>
        }
      >
        <BaseForm
          form={form}
          ref={createFormRef}
          list={createList(t, createSubmit)}
          data={createData}
          labelCol={{ style: { width: 'max-content' } }}
          handleFinish={handleCreate}
        />
      </BaseModal>

      <FloatButton.BackTop />
    </BaseContent>
  );
}

export default Page;
